package com.siboxuetang.need.service.impl;

import com.siboxuetang.need.persist.mybatis.UserMapper;
import com.siboxuetang.need.persist.mybatis.WechatUserMapper;
import com.siboxuetang.need.service.UserService;
import com.siboxuetang.need.util.ResultCode;
import com.siboxuetang.need.util.StringUtrils;
import com.siboxuetang.need.vo.NeedException;
import com.siboxuetang.need.vo.ResultBean;
import com.siboxuetang.need.vo.User;
import com.siboxuetang.need.vo.WechatUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Create Time: 2018年04月26日 17:34
 *
 * @author fin
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatUserMapper wechatUserMapper;


    /**
     * 根据openid获取用户信息
     *
     * @param openid openid
     * @param origin 平台来源 0： 公众号 1：小程序
     * @return 用户信息结果
     */
    @Override
    public ResultBean<User> getUserByOpenid(String openid, int origin) {
        User user = userMapper.findUserByOpenid(openid, origin);
        if(user == null){
            return new ResultBean<>(ResultCode.NO_USER_INFO, "没有该用户信息");
        }else if(user.getUserStatus().equals(1)){
            return new ResultBean<>(ResultCode.USER_UNABLED, "账号已冻结，无法登陆");
        }else {
            user.setUserLastLoginTime(new Date());
            userMapper.updateByPrimaryKey(user);
            return new ResultBean<>(user);
        }

    }

    /**
     * 微信平台注册用户
     *
     * @param openid 用户识别
     * @param origin 平台来源 0：公众号 1：小程序
     * @return 注册结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<User> registUser(String openid, int origin) {
        User user = new User();
        WechatUser wechatUser = new WechatUser();
        wechatUser.setId(StringUtrils.UUID());
        wechatUser.setIsDeleted((byte) 0);
        wechatUser.setWechatType((byte) origin);
        wechatUser.setWechatOpenId(openid);
        user.setId(StringUtrils.UUID());
        user.setIsDeleted((byte) 0);
        user.setUserOrigin((byte) (origin + 2));
        int i = this.userMapper.addWechatUser(user);
        if(i == 0){
            throw new NeedException(ResultCode.REGIST_ERROR,"插入失败");
        }
        i = this.wechatUserMapper.addWechatUser(wechatUser);
        if(i == 0){
            throw new NeedException(ResultCode.REGIST_ERROR,"插入失败");
        }else{
            return new ResultBean<>(user);
        }
    }

}
